﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TaskAdvanceDemo
{
    public partial class FrmTask : Form
    {
        public FrmTask()
        {
            InitializeComponent();
        }

        //取消任务信号源对象
        private CancellationTokenSource cts = new CancellationTokenSource();

        //手动停止事件对象
        private ManualResetEvent mResetEvent = new ManualResetEvent(true);

        //启动
        private void button1_Click(object sender, EventArgs e)
        {
            if(cts.IsCancellationRequested)
            {
                cts = new CancellationTokenSource(); //如果任务取消,则重新创建一个
            }
            Task task = new Task(() =>
            {
                int counter = 0;
                while (!cts.IsCancellationRequested)
                {
                    //用来控制是否需要暂停和继续
                    mResetEvent.WaitOne();

                    //实际开发中可以在这个地方编写你要循环的任务...

                    counter++;
                    Thread.Sleep(300);
                    Console.WriteLine(counter);
                }
            },cts.Token);
            task.Start();
        }

        //取消
        private void button2_Click(object sender, EventArgs e)
        {
            cts.Cancel(); //只需要调用这个取消方法即可
        }

        //暂停
        private void button3_Click(object sender, EventArgs e)
        {
            mResetEvent.Reset();
        }

        //继续
        private void button4_Click(object sender, EventArgs e)
        {
            mResetEvent.Set();
        }
    }
}
